package com.qg.cyapp.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;

import com.google.gson.Gson;
import com.qg.cyapp.bean.GsonBean;
import com.qg.cyapp.util.HttpUtil;
import com.qg.cyapp.util.ShareUtil;

/**
 * @author xuan 2014-10-30
 * 
 */
// 与网络相关的Activity基类
public abstract class HttpActivity extends BaseActivity {

	private List<PostPacket> requestList = new ArrayList<PostPacket>();
	protected Map<String, String> params = new HashMap<String, String>();
	protected GsonBean bean;
	protected Gson gson = ShareUtil.gson;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	// 发送请求关键函数
	public synchronized void sendPostRequest() {
		if (requestList.size() == 0) {
			return;
		}
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				final PostPacket pp = requestList.get(0);
				requestList.remove(0);
				try {
					final String result = HttpUtil.doPost(ShareUtil.BASE_URL
							+ pp.url, pp.params);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							afterPost(result, pp.requestCode, pp.params);
						}
					});
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	// 添加发送请求
	public void addPostRequest(String url, Map<String, String> params,
			int requestCode) {
		requestList.add(new PostPacket(url, params, requestCode));
	}

	// 发送请求bean
	class PostPacket {
		String url;
		Map<String, String> params = new HashMap<String, String>();
		int requestCode;

		public PostPacket(String url, Map<String, String> params,
				int requestCode) {
			// TODO Auto-generated constructor stub
			this.url = url;
			this.params.putAll(params);

			this.requestCode = requestCode;
		}
	}

	public GsonBean getGsonBean(String result) {
		try {
			if (result != null) {
				return ShareUtil.gson.fromJson(result, GsonBean.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (new GsonBean(ShareUtil.FAIL));
	}

	// 待完成函数,发送请求后回调该函数
	public abstract void afterPost(String result, int requestCode,
			Map<String, String> request);

}
